import { useEffect } from 'react';

import { Button, Form, Input, InputNumber, Modal, Radio, Upload, UploadFile } from 'antd';
import { useModel } from '@umijs/max'
import { Adv, AdvInfoType, AdvOpenType, AdvPlaceType, AdvShow, editAdv } from './services';
import { useRequest } from 'ahooks';
import { enum2options } from '@/utils/enum2options';
import { SUCCESS_CODE } from '@/constants';
import { PlusOutlined } from '@ant-design/icons';
import StationSelect from '@/components/StationSelect';
import CouponSelect from '@/components/CouponSelect';
import { RcFile } from 'antd/es/upload';

const BannerImgConfig = {
  width: 700, height: 280, size: 2,
}
const ModalImgConfig = {
  width: 600, height: 800, size: 2,
}

const RoleEditPage: React.FC<RoutePageProps> = (props) => {
  const [editForm] = Form.useForm()
  const { runAsync, loading } = useRequest(editAdv, {manual: true})
  const { closeCurrentTab } = useModel('global')

  const onFinish = (formValues: any) => {
    runAsync({
      id: formValues.id,
      openType: formValues.openType,
      placeType:formValues.placeType,
      infoType: formValues.infoType,
      isShow: formValues.isShow,
      infoId: formValues.info ? formValues.info[0].id : undefined,
      infoName: formValues.info ? formValues.info[0].name : undefined,
      power: formValues.power,
      pic: formValues.pic[0].url,
    })
    .then(() => {
      const event = new CustomEvent('refreshAdvList')
      window.dispatchEvent(event)
      closeCurrentTab('/advertisement/list')
    })
  }

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  }

  const beforeUpload = async (file: RcFile) => {
    return Promise.resolve()
    const openType = editForm.getFieldValue('openType')
    if (openType === AdvOpenType.弹窗) {
      if (file.size > 1024 * 1024 * ModalImgConfig.size) {
        Modal.warn({
          title: '提示',
          content: `请选择体积小于 ${ModalImgConfig.size}M 的图片`
        })
        return Upload.LIST_IGNORE
      }
    } else {
      if (file.size > 1024 * 1024 * BannerImgConfig.size) {
        Modal.warn({
          title: '提示',
          content: `请选择体积小于 ${BannerImgConfig.size}M 的图片`
        })
        return Upload.LIST_IGNORE
      }
    }
    const reader = new FileReader()
    reader.readAsDataURL(file)
    const base64 = await new Promise((resolve) => {
      reader.onload = () => {
        resolve(reader.result)
      }
    })
    const img = new Image()
    img.src = base64 as string
    const res: {width: number, height: number} = await new Promise((resolve) => {
      img.onload = () => {
        resolve({
          width: img.width,
          height: img.height
        })
      }
    })
    if (openType === AdvOpenType.弹窗) {
      if (res.width !== ModalImgConfig.width || res.height !== ModalImgConfig.height) {
        Modal.warn({
          title: '提示',
          content: `请选择尺寸为 ${ModalImgConfig.width} * ${ModalImgConfig.height} 的图片`
        })
        return Upload.LIST_IGNORE
      }
    } 
    if (res.width !== BannerImgConfig.width || res.height !== BannerImgConfig.height) {
      Modal.warn({
        title: '提示',
        content: `请选择尺寸为 ${BannerImgConfig.width} * ${BannerImgConfig.height} 的图片`
      })
      return Upload.LIST_IGNORE
    }
    return Promise.resolve()
  }

  const onFileUpLoadChange = (file: UploadFile) => {
    const { status, response } = file
    if (status === 'done' && response) {
      const { code, data, text } = response
      if (code === SUCCESS_CODE) {
        editForm.setFieldsValue({
          pic: [{status: 'done', url: data}]
        })
      } else {
        Modal.error({
          title: '错误',
          content: text === '上传文件过大' ? '文件体积超过 2M，请重新上传' : '图片上传失败，请重试',
        })
        editForm.setFieldsValue({
          pic: []
        })
      }
    }
  }

  const onValuesChange = (values: any) => {
    if (values.infoType) {
      editForm.setFieldsValue({info: undefined})
    } else if (values.openType) {
      editForm.setFieldsValue({pic: undefined})
    }
  }

  useEffect(() => {
    if (props.params.type === 'add') {
      editForm.setFieldsValue({
        id: undefined,
        openType: AdvOpenType.轮播图,
        placeType: AdvPlaceType.小程序首页,
        infoType: AdvInfoType.电站,
        isShow: AdvShow.展示,
        info: undefined,
        power: undefined,
        pic: undefined,
      })
    } else {
      const dataStr = sessionStorage.getItem('_advRecord')
      if (dataStr) {
        const data: Adv = JSON.parse(dataStr)
        editForm.setFieldsValue({
          id: data.id,
          openType: data.openType,
          placeType: data.placeType,
          infoType: data.infoType,
          isShow: data.isShow,
          info: data.infoId ? [{id: data.infoId, name: data.infoName}] : undefined,
          power: data.power,
          pic: [{status: 'done', url: data.pic}],
        })
      }
    }
  }, [props.params.type])
  
  return (
    <div className='container'>
      <div className="card">
        <Form form={editForm} name='editForm' labelCol={{flex: '120px'}} onFinish={onFinish} onValuesChange={onValuesChange}>
          <Form.Item name='id' noStyle>
            <Input hidden />
          </Form.Item>
          <Form.Item name='placeType' label='展示位置' rules={[{required: true, message: '请选择展示位置'}]}>
            <Radio.Group options={enum2options(AdvPlaceType)} />
          </Form.Item>
          <Form.Item name='openType' label='展示方式' rules={[{required: true, message: '请选择展示方式'}]}>
            <Radio.Group options={enum2options(AdvOpenType)} />
          </Form.Item>
          <Form.Item name='infoType' label='关联类型' rules={[{required: true, message: '请选择关联类型'}]}>
            <Radio.Group options={enum2options(AdvInfoType)} />
          </Form.Item>
          <Form.Item dependencies={['infoType']} noStyle>
            {
              ({getFieldValue}) => {
                const infoType = getFieldValue('infoType')
                if (infoType === AdvInfoType.无) return null
                if (infoType === AdvInfoType.电站) {
                  return <Form.Item name='info' label='电站' rules={[{required: true, message: '请选择电站'}]}>
                    <StationSelect style={{width: 320}} />
                  </Form.Item>
                }
                return <Form.Item name='info' label='优惠券' rules={[{required: true, message: '请选择优惠券'}]}>
                  <CouponSelect style={{width: 320}} />
                </Form.Item>
              }
            }
          </Form.Item>
          <Form.Item name='isShow' label='是否展示' rules={[{required: true, message: '请选择是否展示'}]}>
            <Radio.Group options={enum2options(AdvShow)} />
          </Form.Item>
          <Form.Item name='power' label='权重' rules={[{required: true, message: '请输入权重'}]}>
            <InputNumber placeholder='请输入' style={{width: 320}} min={0} precision={0} />
          </Form.Item>
          <Form.Item label="图片" required>
            <Form.Item
              name='pic' rules={[{required: true, message: '请上传图片'}]} 
              valuePropName="fileList" getValueFromEvent={normFile} noStyle
            >
              <Upload 
                action="/app/user/fileUp" listType="picture-card"
                data={{type: 1}} maxCount={1}
                headers={{Authorization: localStorage.Authorization}}
                beforeUpload={beforeUpload}
                onChange={({file}) => onFileUpLoadChange(file)}
                accept='.jpg, .png'
              >
                <button style={{ border: 0, background: 'none' }} type="button">
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>选择照片</div>
                </button>
              </Upload>
            </Form.Item>
            <div>
              提示：轮播图请上传 {BannerImgConfig.width} * {BannerImgConfig.height} 尺寸，体积小于 {BannerImgConfig.size}M 的图片；
              弹窗图请上传 {ModalImgConfig.width} * {ModalImgConfig.height} 尺寸，体积小于 {ModalImgConfig.size}M 的图片
            </div>
          </Form.Item>
          <Form.Item label=' ' colon={false}>
            <Button type='primary' htmlType='submit' loading={loading}>提交</Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default RoleEditPage;
